# -*- coding: utf-8 -*-
# @Time: 2023/4/17 10:14
# @File: common.py
# @Desc:

from exts import db
from datetime import datetime
from sqlalchemy_serializer import SerializerMixin


# 板块模型
class Board(db.Model, SerializerMixin):
    serialize_only = ("id", "name", "priority", "create_date")
    __tablename__ = "board"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 板块id
    name = db.Column(db.String(50), unique=True, nullable=False)  # 板块名称
    priority = db.Column(db.Integer, default=1)  # 板块优先级
    create_date = db.Column(db.DateTime, default=datetime.now)  # 创建时间


# 轮播图模型
class Banner(db.Model, SerializerMixin):
    __tablename__ = "banner"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 轮播图ID
    name = db.Column(db.String(255), nullable=False)  # 轮播图名称
    img_url = db.Column(db.String(255), nullable=False)  # 轮播图url
    url_to = db.Column(db.String(255), nullable=False)  # 轮播图跳转url
    priority = db.Column(db.Integer, default=0)  # 轮播图优先级
    create_date = db.Column(db.DateTime, default=datetime.now)


# 帖子模型
class Post(db.Model, SerializerMixin):
    serialize_only = ("id", "title", "content", "create_date", "board", "author")
    __tablename__ = "post"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 帖子id
    title = db.Column(db.String(255), nullable=False)  # 帖子名称
    content = db.Column(db.Text, nullable=False)  # 帖子内容
    board_id = db.Column(db.Integer, db.ForeignKey("board.id"))  # 所属板块id
    author_id = db.Column(db.String(255), db.ForeignKey("user.id"), nullable=False)  # 所属用户id
    create_date = db.Column(db.DateTime, default=datetime.now)  # 发布时间
    # 多表关系关联
    board = db.relationship("Board", backref=db.backref("posts"))
    author = db.relationship("User", backref=db.backref("posts"))


# 评论模型
class Comment(db.Model, SerializerMixin):
    __tablename__ = 'comment'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 评论id
    content = db.Column(db.Text, nullable=False)  # 评论内容
    create_date = db.Column(db.DateTime, default=datetime.now)  # 发布时间
    post_id = db.Column(db.Integer, db.ForeignKey("post.id"))  # 所属帖子id
    user_id = db.Column(db.String(255), db.ForeignKey("user.id"), nullable=False)  # 所属用户id
    # 多表关联关系
    # 级联删除 post表删除帖子时，帖子相关的评论也会一起被删除
    post = db.relationship(
        "Post",
        backref=db.backref(
            "comments",
            order_by="Comment.create_date.desc()",
            cascade="delete, delete-orphan"
        )
    )
    author = db.relationship("User", backref="comments")
